package com.lsh.oms.core.records;

import com.lsh.base.lang.Maps;
import com.lsh.base.lang.json.Jsons;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.lsh.base.lang.bean.Beans.getMap;
import static com.lsh.base.lang.bean.Beans.getString;
import static com.lsh.oms.core.records.core.Return.Status.*;

public class AfterSaleDiscardReturn extends AfterSaleReturn {

    private static final Logger LOGGER = LoggerFactory.getLogger(AfterSaleDiscardReturn.class);

    @Override
    public void start() {
        run(Collections.emptyMap());
    }

    @Override
    public void run(Map<String, Object> request) {
        preDeliver(request);
    }

    @Override
    public void preDeliver(Map<String, Object> request) {
        deliver(request);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deliver(Map<String, Object> request) {
        LOGGER.info("return: {} deliver with request: {}", id, request);

        change($ -> $.status = DELIVERED, PENDING, PRE_DELIVER);

        tasks.addHttpTrigger(id, venderId, Maps.newHashMap("method", "POST", "url", refundTarget(), "entity", Collections.emptyMap()));

        List<Map<String, Serializable>> forCheck = details.stream().map($ -> ((ReturnDetailRecord) $)).map($ -> {
            LOGGER.info("after sale return detail: {}, build check request with: {}", $.id, Jsons.toJsonString($.ext));
            Map<String, Object> opinion = getMap($.ext, "opinion");
            String key = (getString(opinion, "take_responsibility") + "_take_responsibility").toLowerCase();
            return Maps.newHashMap("id", $.id, key, Maps.newHashMap("quantity", $.actualQuantity, "discarded_reason", getString(opinion, "discarded_reason")));
        }).collect(Collectors.toList());

        check(Maps.newHashMap("details", forCheck, "checked_by", "SUPPORT_STAFF"));
        confirm(request);
    }
}
